<template>
  <el-dialog
    :title="isEdit ? '编辑门店' : '添加门店'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="900px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="store-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="门店名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入门店名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店长" prop="manager">
            <el-select v-model="form.manager" placeholder="请选择店长" style="width: 100%">
              <el-option 
                v-for="manager in managers" 
                :key="manager._id || manager.id" 
                :label="manager.name" 
                :value="manager.name" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="员工数" prop="staffCount">
            <el-input v-model="form.staffCount" disabled placeholder="自动计算" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="营业中" value="营业中" />
          <el-option label="暂停营业" value="暂停营业" />
          <el-option label="装修中" value="装修中" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="form.address"
          type="textarea"
          :rows="3"
          placeholder="请输入详细地址"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'
import { EMPLOYEE_API } from '../config/api'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  storeData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'submit'])

// 表单引用
const formRef = ref()
const loading = ref(false)

// 员工列表（老板和管理员）
const managers = ref([])



// 表单数据
const form = reactive({
  name: '',
  address: '',
  phone: '',
  manager: '',
  staffCount: 0,
  status: '营业中'
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入门店名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  manager: [
    { required: true, message: '请选择店长', trigger: 'change' }
  ],

  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取老板和管理员列表
const loadManagers = async () => {
  try {
    const response = await request.get(EMPLOYEE_API.GET_EMPLOYEES)
    
    if (response.data && response.data.success) {
      const allEmployees = response.data.data || []
      // 筛选出老板和管理员
      managers.value = allEmployees.filter(emp => 
        emp.role === '老板' || emp.role === 'owner' || 
        emp.role === '管理员' || emp.role === 'manager'
      )
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
  }
}

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (props.isEdit && props.storeData) {
        // 处理MongoDB的_id字段
        const { _id, ...storeData } = props.storeData
        Object.assign(form, storeData)
      }
    })
  }
})

// 组件挂载时加载员工列表
onMounted(() => {
  loadManagers()
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    emit('submit', { ...form })
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  // 重置表单
  Object.assign(form, {
    name: '',
    address: '',
    phone: '',
    manager: '',
    staffCount: 1,
    status: '营业中'
  })
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}


</script>

<style scoped>
.store-form {
  max-height: 70vh;
  overflow-y: auto;
}



.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .store-form {
    max-height: 60vh;
  }
}
</style> 